/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package org.example.modules.sys.controller;

import org.example.common.utils.R;
import org.example.modules.sys.dto.LoginDto;
import org.example.modules.sys.dto.RegisterDto;
import org.example.modules.sys.entity.SysUserEntity;
import org.example.modules.sys.service.SysCaptchaService;
import org.example.modules.sys.service.SysLoginService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.example.modules.sys.service.SysUserRoleService;
import org.example.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysLoginService sysLoginService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody LoginDto loginDto)throws IOException {
		//生成token
		String token = sysLoginService.login(loginDto);

		return R.ok().put("token",token);
	}

	/**
	 * 注册
	 */
	@PostMapping("/sys/register")
	public Map<String, Object> register(@RequestBody RegisterDto registerDto)throws IOException {
		//生成token，并保存到数据库
		String token = sysLoginService.register(registerDto);

		return R.ok().put("token",token);
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysLoginService.logout();
		return R.ok();
	}
	
}
